<script setup name="Identify">
import { getCurrentInstance, ref, shallowRef } from "vue";
import { 
	getAssociationCertificatePage,
	getAssociationCertificateByKey,
	addAssociationCertificate,
	editAssociationCertificate,
	delAssociationCertificate
 } from "@/api/company/associationCertificate";
import Pagination from "@/components/Pagination/index.vue";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const queryForm = shallowRef(null);
const queryParams = ref({
	searchText: null,
	pageNum: 1,
	pageSize: 10,
});
const total = ref(0);
const tFlag = [
	{
		label: '是',
		value: '1',
		elTagType: 'primary',
	},
	{
		label: '否',
		value: '0',
		elTagType: 'danger'
	},
]
const rowId = ref(null);
const loading = ref(false);

const tableData = ref([]);

const editVisible = ref(false);

// 查询
const search = async () => {
	await getTableData();
};

// 获取列表
const getTableData = async () => {
	loading.value = true;
	const res = await getAssociationCertificatePage({...queryParams.value});
	try {
		console.log(res);
		if (res.code === 200) {
			tableData.value = res.data.records;
			total.value = res.data.total;
		}
	} catch (e) {
		console.log(e);
	} finally {
		setTimeout(() => {
			loading.value = false;
		}, 1e3);
	}
};

// 新增
const add = () => {
	editVisible.value = true;
	formData.value = {
		name: null,
		sort: null,
		photoFileIds: [],
		fileUrl: null,
		desc: null,
		isView: 1
	}
};
// 编辑
const handleUpdate = (row) => {
	editVisible.value = true;
	rowId.value = row.id;
	getDetailData()
};

const getDetailData = async () => {
	const res = await getAssociationCertificateByKey({id: rowId.value})
	if(res.code === 200) {
		formData.value = {
			...res.data,
			fileUrl: res.data.photoFiles?.length ? res.data.photoFiles[0].accessUrl : null,
			photoFileIds: res.data.photoFiles?.length ? [res.data.photoFiles[0].id] : []
		}
	}
}

// 删除
const handleDelete = (row) => {
	const id = row.id;
	proxy.$modal
		.confirm('是否确认删除企业证书编号为"' + id + '"的数据项?')
		.then(async function () {
			return delAssociationCertificate({ id });
		})
		.then(() => {
			getTableData();
			proxy.$modal.msgSuccess("删除成功");
		})
		.catch(() => {});
};

const formData = ref({
	name: null,
	sort: null,
	photoFileIds: [],
	fileUrl: null,
	desc: null,
	isView: 1
});

const fileAction = import.meta.env.VITE_APP_BASE_API + "/associationCertificate/addPhotoImg";

const rules = {
	name: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
	addr: [{ required: true, message: "请输入企业地址", trigger: "blur" }],
	grade: [{ required: true, message: "请输入证书等级", trigger: "change" }],
	fileUrl: [{ required: true, message: "请上传证书", trigger: "blur" }]
};
const clearFile = () => {
	formData.value.fileUrl = null;
	formData.value.photoFileIds = [];
	proxy.$refs["fileId"].clearFiles();
};

const photoBeforeUpload = (file) => {
	let isRightSize = file.size / 1024 / 1024 < 20;
	if (!isRightSize) {
		proxy.$modal.msgError("文件大小超过 20MB");
	}
	return isRightSize;
};
const handleRemove = (file, fileList) => {
	formData.value.fileUrl = null;
	formData.value.photoFileIds = [];
};
const uploadSuccess = (response, file, fileList) => {
	if (response.code === 200) {
		formData.value.photoFileIds = response.data.id ? [response.data.id] : [];
		formData.value.fileUrl = response.data.accessUrl;
	} else {
		formData.value.photoFileIds = [];
		formData.value.fileUrl = null;
	}
};

const closeDialog = () => {
	editVisible.value = false;
	clearFile();
	proxy.resetForm("elForm");
};

const onClose = async () => {
	rowId.value = null;
	clearFile();
};

const submitForm = async () => {
	proxy.$refs["elForm"].validate(async (valid) => {
		if (valid) {
			const params = {
				...formData.value,
			};
			if (params.createTime) delete params.createTime;
			if (params.fileUrl) delete params.fileUrl;
			if (params.updateTime) delete params.updateTime;
			let res;
			if (rowId.value) {
				res = await editAssociationCertificate(params);
			} else {
				res = await addAssociationCertificate(params);
			}
			try {
				if (res.code === 200) {
					closeDialog();
					await getTableData();
				}
			} catch (e) {
				console.log(e);
			}
		}
	});
};

getTableData();
</script>

<template>
	<div class="app-container">
		<el-form ref="queryForm" :model="queryParams" inline label-width="68px" @submit.native.prevent>
			<el-form-item label="关键字" prop="searchText">
				<el-input
					:style="{ width: '200px' }"
					v-model="queryParams.searchText"
					clearable
					placeholder="请输入关键字">
				</el-input>
			</el-form-item>
			<el-form-item>
				<el-button :disabled="loading" icon="Search" type="primary" @click="search">搜索 </el-button>
				<el-button :disabled="loading" type="primary" @click="add">添加证书</el-button>
			</el-form-item>
		</el-form>
		<el-table v-loading="loading" :data="tableData">
			<el-table-column :show-overflow-tooltip="true" label="证书名称" prop="name" />
			<el-table-column label="是否显示" prop="isView">
				<template #default="scope">
					<dict-tag :options="tFlag" :value="String(scope.row.isView)"/>
				</template>
			</el-table-column>
			<el-table-column label="排序值" prop="sort"/>
			<el-table-column label="添加时间" prop="createTime" />
			<el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="160">
				<template #default="scope">
					<el-button icon="Edit" link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
					<el-button icon="Delete" link type="danger" @click="handleDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="search"></pagination>

		<el-dialog :title="rowId ? '编辑证书' : '添加证书'" append-to-body destroy-on-close center v-model="editVisible" @close="onClose">
			<el-form ref="elForm" :model="formData" :rules="rules" label-width="100px" :size="'default'">
				<el-form-item label="证书名称" prop="name">
					<el-input v-model="formData.name" :style="{ width: '100%' }" clearable placeholder="请输入证书名称"></el-input>
				</el-form-item>
				<el-form-item label="证书照片" prop="fileUrl">
					<el-upload
						ref="fileId"
						:accept="'.jpg,.jpeg,.png'"
						:action="fileAction"
						:before-upload="photoBeforeUpload"
						:headers="{
							Authorization: 'Bearer ' + getToken(),
						}"
						:limit="1"
						:list-type="'picture'"
						:on-remove="handleRemove"
						:on-success="uploadSuccess"
						:show-file-list="false">
						<el-button :disabled="formData.fileUrl !== null && formData.fileUrl !== ''" icon="Upload" :size="'small'" type="primary"
							>点击上传
						</el-button>
						<el-button size="small" type="warning" @click.stop="clearFile">清空上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item v-if="formData.fileUrl" prop="fileUrl">
					<el-image :preview-src-list="[formData.fileUrl]" :src="formData.fileUrl" style="width: 100px; height: 100px"> </el-image>
				</el-form-item>
				<el-form-item label="简述" prop="desc">
					<el-input
						v-model="formData.desc"
						:autosize="{ minRows: 4, maxRows: 4 }"
						:style="{ width: '100%' }"
						placeholder="请输入简述"
						type="textarea"></el-input>
				</el-form-item>
				<el-form-item label="排序值" prop="sort">
					<el-input-number v-model="formData.sort" clearable placeholder="排序值" :step="1" :min="0"></el-input-number>&nbsp;&nbsp;排序值越小越靠前
				</el-form-item>
				<el-form-item label="是否显示" prop="isView">
					<el-switch v-model="formData.isView" :active-value="1" :inactive-value="0" active-text="显示" inactive-text="不显示"></el-switch>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="closeDialog">取消</el-button>
					<el-button type="primary" @click="submitForm">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<style lang="scss" scoped>
.pagination-container {
	background: #fff;
	padding: 32px 16px;
}
.pagination-container.hidden {
	display: none;
}
</style>
